package middleware

import (
	"finance/internal/models"
	"finance/internal/utils"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

func PermissionMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		roleID := c.GetUint("roleID")
		path := c.FullPath()       // 当前请求路径
		method := c.Request.Method // 当前请求的方法(post,get...)

		fmt.Println(roleID, path, method)

		var count int64
		err := models.DB.
			Table("permissions AS p").
			Joins("JOIN role_permissions rp ON rp.permission_id = p.id").
			Where("rp.role_id = ? AND p.path = ? AND (p.method = ? OR p.method IS NULL)", roleID, path, method).
			Count(&count).Error

		if err != nil || count == 0 {
			utils.Fail(c, http.StatusForbidden, "permission denied")
			c.Abort()
			return
		}
		c.Next()
	}
}
